package Network;

import java.net.*;
/**
 * La classe UDP <br>
 * @author Romain Bustos
 * @author Matthieu Perrin
 * @version 1.0
 */
public class ClientUDP 
{

    final static int TAILLE_MAX_BUFFER=100;
    final static int PORT_SERVEUR = 2510;
    
    InetAddress addr;
    int port = 2510;
    byte[] bufferin = new byte[TAILLE_MAX_BUFFER];
    String reponse = "";
    String commande;
    DatagramPacket inPacket = null;
    DatagramPacket outPacket = null;
    DatagramSocket datagramSocket;
    
    /**
    *<b>Constructeur ClientUDP</b>
    * @return IP, port
    */
    public ClientUDP(String IP, int num_port) throws SocketException, UnknownHostException{        
        // socket crée sur un port disponible choisit pas l'OS
	//datagramSocket = new DatagramSocket();
        
        try{
            datagramSocket = new DatagramSocket();
        }
        catch(Exception e){
            datagramSocket = new DatagramSocket(2588);
            System.out.println("client on port 2588.");
        }
        
        this.port = num_port;
        addr = InetAddress.getByName(IP);
    }
    
    public ClientUDP(String IP) throws SocketException, UnknownHostException{        
        // socket crée sur un port disponible choisit pas l'OS
	datagramSocket = new DatagramSocket();
        addr = InetAddress.getByName(IP);
    }
        
    /**
    *<b>Methode SetPort</b>
    *  Modifie sur le port sur lequel envoyer
    * @return port
    */
    public void SetPort(int num_port){
        this.port = num_port;
    }
   
     
    /**
    *<b>Methode SetAddress</b>
    *  Modifie l'adresse sur laquel envoyer
    * @return IP
    */
    public void SetAddress(String IP) throws UnknownHostException{        
	addr = InetAddress.getByName(IP);
    }
        
    /**
    *<b>Methode Push</b>
    * Envoie les donné passé en parametres
    * @return data
    */
    public void Push(byte[] data ) throws SocketException{
        datagramSocket.setSendBufferSize(data.length);
        try { 
	    outPacket = new DatagramPacket(data,data.length,addr,port);
            //System.out.println("donnes envoyé" +data.length);
	    datagramSocket.send(outPacket);
            Thread.sleep(20);
	    }
	catch(UnknownHostException e){ System.err.println(e); }
	catch(Exception e) { System.err.println(e); }
    }
    
    
}
